package com.mapfinal.server.geoserver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.lambkit.Lambkit;
import com.lambkit.common.LambkitResult;
import com.lambkit.core.gateway.GatewayService;

/**
 * 地图服务/
 * Geoserver-wms/wfs/wmts/
 * ArcGIS Server-wms/wfs/
 * SuperMap-wms/wfs/
 * BMap-map
 * AMap-map
 * Tianditu-map
 * @author yangyong
 *
 */
public class GeoserverController extends Controller {
	/**
	 * geoserver map service
	 * 
	 * ---------------------
	service:WMS
	version:1.1.0
	request:GetMap
	layers:map:152201
	styles:
	bbox:122.064245518,45.79297386500008,122.39529004900004,46.02589016600005
	width:768
	height:540
	srs:EPSG:4326
	format:application/openlayers
	 * ---------------------
	 */
	public void index() {
		String service = getPara("service");
		if("WMS".equalsIgnoreCase(service)) {
			render(GeoserverManager.me().getDefaultServer().wms("map/geoserver"));
		} else if("WFS".equalsIgnoreCase(service)) {
			render(GeoserverManager.me().getDefaultServer().wfs("map/geoserver"));
		} else {
			renderError(404);
		}
	}
	
	/**
	 * geoserver wfs service
	 * 点所在的要素
	 */
	public void pts() {
		String filter= "<Filter xmlns=\"http://www.opengis.net/ogc\" xmlns:gml=\"http://www.opengis.net/gml\"><Intersects><PropertyName>the_geom</PropertyName><gml:Point><gml:coordinates>";
		filter += getPara("point");
		filter += "</gml:coordinates></gml:Point></Intersects></Filter>";
		Map<String, String> params = new HashMap<>();
		params.put("service", "WFS");
		params.put("request", "GetFeature");
		params.put("version", "1.0.0");
		params.put("typeName", getPara("layer"));
		params.put("maxFeatures", "2000");
		params.put("outputFormat", "json");
		params.put("filter", filter);
		GeoserverConfig config = Lambkit.config(GeoserverConfig.class);
		String targetUri = config.getUrl() + "/" + config.getWorkspace() + "/wfs";
		String result = GatewayService.by(this).get("map/geoserver/pts", targetUri, params);
		renderJson(result);
	}
	
	/**
	 * geoserver的包围盒
	 */
	public void bbox() {
		String layer = getPara(0);
		GeoserverConfig config = Lambkit.config(GeoserverConfig.class);
		String targetUri = config.getUrl() + "/" + config.getWorkspace() + "/wms";
		if (StrKit.notBlank(layer)) {
			Document doc;
			try {
				doc = Jsoup
						.connect(
								targetUri + "?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetCapabilities")
						.timeout(3000).get();
				Elements layers = doc.getElementsByTag("layer");
				List<Map<String, Object>> data = new ArrayList<>();
				for (Element element : layers) {
					String queryable = element.attr("queryable");
					if (!"1".equals(queryable)) {
						continue;
					}
					String name = "0", title = null, bbox = null;
					Elements names = element.getElementsByIndexEquals(0);
					if (names != null && names.get(0) != null) {
						if ("name".equals(names.get(0).nodeName())) {
							name = names.get(0).text();
						}
					}
					Elements titles = element.getElementsByTag("Title");
					Elements bboxs = element.getElementsByTag("EX_GeographicBoundingBox");
					if (titles != null && titles.get(0) != null) {
						title = titles.get(0).text();
					}
					if (bboxs != null && bboxs.get(0) != null) {
						String minx = bboxs.get(0).getElementsByTag("westboundlongitude").get(0).text();
						String miny = bboxs.get(0).getElementsByTag("southBoundLatitude").get(0).text();
						String maxx = bboxs.get(0).getElementsByTag("eastBoundLongitude").get(0).text();
						String maxy = bboxs.get(0).getElementsByTag("northBoundLatitude").get(0).text();
						bbox = minx + "," + miny + "," + maxx + "," + maxy;
					}
					// System.out.println("name=" + name + ", title=" + title +
					// ", bbox=" + bbox);
					Map<String, Object> one = new HashMap<>();
					one.put("name", name);
					one.put("title", title);
					one.put("bbox", bbox);
					data.add(one);
				}
				renderJson(new LambkitResult(1, "success", data));
			} catch (IOException e) {
				e.printStackTrace();
				renderJson(new LambkitResult(0, "fail", "IOException"));
			}
		} else {
			renderJson(new LambkitResult(0, "fail", "layer is null"));
		}
	}
}
